package woncode.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DownloadController {
	
	@RequestMapping("/DownloadFile")
	public synchronized void transferFile(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, InterruptedException{
		int fileID=Integer.parseInt(req.getParameter("fileID"));
		System.out.println("DownloadFile: fileID="+fileID);
		ArrayList<Object> fileContextList=UtilContext.fileContextMap.get(fileID);
		while (fileContextList.size() < 3) {
			fileContextList.add(this);
			WebSocketController webSocketController=(WebSocketController) fileContextList.get(0);
			webSocketController.sendStartUpload();
			this.wait();
		}
		UploadController uploadController=(UploadController)fileContextList.get(2);
		resp.setHeader("Accept-Ranges","none");
		resp.setContentType("multipart/form-data");
		resp.setHeader("content-disposition", "attachment;filename="+uploadController.fileName);
		ServletOutputStream servletOutputStream=resp.getOutputStream();
		while(!uploadController.isFinish){
			servletOutputStream.write(uploadController.bytes);
			uploadController.selfNotifyAll();
			this.wait();
		}
		servletOutputStream.close();
		UtilContext.fileContextMap.remove(fileID);
		System.out.println("dowload ok");

//		Enumeration<String> h=req.getHeaderNames();
//		while (h.hasMoreElements()) {
//			String sh=h.nextElement();
//			System.out.print(sh);
//			System.out.println(":"+req.getHeader(sh));
//		}
//		System.out.println("ThreadID: "+Thread.currentThread().getId());
//		File downloadFile=new File("F:\\Download\\MediaCreationTool.exe");
//		resp.setContentType("multipart/form-data");
//		resp.setHeader("content-disposition", "attachment;filename=MediaCreationTool.exe");
//		FileInputStream fileInputStream=new FileInputStream(downloadFile);
//		ServletOutputStream servletOutputStream=resp.getOutputStream();
//		byte[] bytes = new byte[1024];
//		while(fileInputStream.read(bytes)!=-1){
//			servletOutputStream.write(bytes);
//		}
//		System.out.println("finish OutputStream write");
//		System.out.println("ThreadID: "+Thread.currentThread().getId());
//		fileInputStream.close();
//		servletOutputStream.close();
	}
	
	public synchronized void selfNotifyAll(){
		this.notify();
	}
}
